<?php
/**
*
* @package YubiKey Login
* @version 1.0.3
* @copyright (c) 2010 Tim Schlueter
* @license http://opensource.org/licenses/gpl-license.php GNU Public License 
*
*/

/**
 * @ignore
 */
if (!defined('IN_PHPBB'))
{
    exit;
}

/**
* @package ucp
*/
class ucp_yubikey_login
{
    var $u_action;
    var $tpl_path;
    var $page_title;

    function main($id, $mode)
    {
	global $db, $config, $phpbb_root_path, $phpEx, $user, $template, $error;

	include "{$phpbb_root_path}includes/functions_yubikey.$phpEx";

	$action = isset($_GET['action']) ? request_var('action', '') : false;
	$submit = request_var('submit', '');
	$ucp_i = request_var('i', '');
	$user_id = (int) $user->data['user_id'];
	$deviceid = request_var('device', '0');

	// check it we're using the glitched subsilver version
	if ($submit == $user->lang['YUBIKEY_ADD'])
	{
		$action = 'add';
	}

	$form_name = 'ucp_yubikey_login';
	add_form_key($form_name);

	if ($action == 'add' && !check_form_key($form_name))
	{
		$url_back = append_sid($user->page['page_name'], "i=$ucp_i");
		$link_back = '<br /><br /><a href="' . $url_back . '">&laquo; ' . $user->lang['BACK_TO_PREV'] . '</a>';
		trigger_error($user->lang['FORM_INVALID'] . $link_back, E_USER_WARNING);
	}

	// Perform the requested action
	switch ($action)
	{
		case 'add':
			// Get YubiKey OTP
			$otp = strtolower(trim(request_var('yubikey_otp', '')));
			if($otp != '')
			{
				add_yubikey($otp, $user_id);
			}
		break;

		case 'activate':
		case 'deactivate':
		case 'delete':
			if($deviceid == '0')
				break;
			
			// Check if YubiKey exists and belongs to the user
			$sql = 'SELECT * FROM ' . YUBIKEY_TABLE . ' WHERE deviceid = \'' . $db->sql_escape($deviceid) . '\' AND user_id = ' . $user_id;
			$result = $db->sql_query($sql);
			$row = $db->sql_fetchrow($result);
			$db->sql_freeresult($result);

			if(!$row)
			{
				$err = 'ERROR_INVALID_REQ';

				// assign admin contact
				$err = (!$config['board_contact']) ? sprintf($user->lang[$err], '', '') : sprintf($user->lang[$err], '<a href="mailto:' . htmlspecialchars($config['board_contact']) . '">', '</a>');

				add_error_message($err);
			}
			
			switch ($action)
			{
				case 'activate':
					activate_deactivate_yubikey($deviceid, YUBIKEY_ACTIVE, ($this->u_action) ? $this->u_action : null, false, false);
				break;

				case 'deactivate':
					activate_deactivate_yubikey($deviceid, YUBIKEY_INACTIVE, ($this->u_action) ? $this->u_action : null, false, false);
				break;

				case 'delete':
					// Check if YubiKey OTP is compulsory to login
					$yk_login_method = $config['yubikey_login_method'];
					if($yk_login_method != YUBIKEY_LOGIN_SCHEME_UN_OR_YK_PWD)
					{
                                        	// Yes.
						// Check if this is the only YubiKey user has
						$sql = 'SELECT COUNT(*) count FROM ' . YUBIKEY_TABLE . ' WHERE user_id = ' . $user_id;
						$result = $db->sql_query($sql);
						$row = $db->sql_fetchrow($result);
						$db->sql_freeresult($result);
						if($row && $row['count'] == 1)
						{
							add_error_message($user->lang['ERROR_LAST_YUBIKEY']);
							break;
						}
					}

					// See if confirmation set
					$confirm = isset($_GET['confirm']) ? true : false;
					if (!$confirm)
					{
						$vars = array(
							'i' => $ucp_i,
							'action' => 'delete',
							'device' => $deviceid,
							'confirm' => 'yes',
						);
						$msg .= $user->lang['YUBIKEY_DELETE_CONF'] . $deviceid . ' <a href="' . append_sid("{$this->u_action}    ", $vars) . '">' . $user->lang['YUBIKEY_DELETE'] . '</a> | <a href="' . append_sid("{$this->u_action}") . '">' . $user->lang['CANCEL'] . '</a>';

						add_message($msg);
					}
					else
					{
						delete_yubikey($deviceid, ($this->u_action) ? $this->u_action : null, false, false);
					}
				break;
			}
		break;
	}

	// Get user's YubiKeys
	$yubikeys_exist = false;
	$sql = 'SELECT deviceid, status FROM ' . YUBIKEY_TABLE . ' WHERE user_id = ' . $user_id;
	$result = $db->sql_query_limit($sql, 50);
	while ($row = $db->sql_fetchrow($result))
	{
		$yubikeys_exist = true;

		$active_lang = ($row['status'] == YUBIKEY_ACTIVE)? 'YUBIKEY_DEACTIVATE' : 'YUBIKEY_ACTIVATE';
		$active_value = ($row['status'] == YUBIKEY_ACTIVE) ? 'deactivate' : 'activate';

		$template->assign_block_vars('yubikey', array(
			'DEVICE_ID'		=> $row['deviceid'],
			'STATUS'		=> ($row['status'] == YUBIKEY_ACTIVE)? "Active": "Inactive",
			'U_ACTIVATE_DEACTIVATE'	=> append_sid("{$this->u_action}&amp;action=$active_value&amp;device={$row['deviceid']}"),
			'L_ACTIVATE_DEACTIVATE'	=> $user->lang[$active_lang],
			'U_DELETE'		=> append_sid("{$this->u_action}&amp;action=delete&amp;device={$row['deviceid']}"),
		));
	}
	$db->sql_freeresult($result);

	// Set up the page
	$this->tpl_name	= 'ucp_yubikey_login';
	$this->page_title = 'UCP_YUBIKEY_LOGIN';

	$template->assign_vars(array(
		'L_TITLE'		=> (isset($user->lang[$this->page_title])) ? $user->lang[$this->page_title] : $this->page_title,
		'S_YUBIKEYS_EXIST'	=> $yubikeys_exist,

		'U_ADD'			=> append_sid("{$this->u_action}&amp;action=add"),
		'S_MODE'		=> "view",
	));
    }
}

function add_message($text)
{
	global $template;
	$template->assign_block_vars('yubikey_message', array('MESSAGE' => $text));
}

function add_error_message($text)
{
	global $template;
	$template->assign_block_vars('yubikey_error_message', array('MESSAGE' => $text));
}
?>
